package com.zhentao.service.impl;

import com.zhentao.dto.HistorySearchDto;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.pojo.ApUserSearch;
import com.zhentao.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
 * @Date 2024/6/11 9:53
 * @Author xdm
 **/
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public ResponseResult deleteById(HistorySearchDto dto) {
        //1.校验参数
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //删除
        mongoTemplate.
                remove(Query.query(Criteria.where("id").is(dto.getId())),ApUserSearch.class);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findUserSearch(String userId) {

        Query query = new Query(Criteria.where("userId").is("4"));
        //按照时间倒叙
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    @Async
    @Override
    public void insert(String userId, String keyword) {

        //1.校验参数
        //2.判断当前用户的搜素的关键词是否存在；
        //  ?  userId怎么来
        Query query =
                new Query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch =
                mongoTemplate.findOne(query, ApUserSearch.class, "ap_user_search");

        //3.如果关键字存在，更新创建时间
        if (apUserSearch != null) {
            Update update = new Update();
            update.set("createdTime", new Date());

            mongoTemplate.updateFirst(query, update, ApUserSearch.class);

            return;
        }

        //4.如果关键字不存在
        //4.1判断是否大于10条，如果小于10条，执行添加操作

        //？怎么查询  根据userId去查询

        Query query1 = new Query(Criteria.where("userId").is(userId));

        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<ApUserSearch> apUserSearchList =
                mongoTemplate.find(query1, ApUserSearch.class, "ap_user_search");


        System.out.println("条数" + apUserSearchList.size());

        ApUserSearch apUserSearch1 = new ApUserSearch();
        apUserSearch1.setUserId(userId);
        apUserSearch1.setKeyword(keyword);
        apUserSearch1.setCreatedTime(new Date());

        if (apUserSearchList == null || apUserSearchList.size() < 10) {
            //执行新增操作

            mongoTemplate.save(apUserSearch1);


        } else {
            //已经存在10条了，把最后一条记录给替换掉；
            ApUserSearch lastSearch = apUserSearchList.get(apUserSearchList.size() - 1);

            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastSearch.getId())), apUserSearch1);


        }

    }
}
